package org.example.utimate;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.utimate.entity.Rectangle;

import java.io.IOException;

@WebServlet("/Control")
public class Control extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");
        String lengthStr = request.getParameter("length");
        String widthStr = request.getParameter("width");

        try {
            double length = Double.parseDouble(lengthStr);
            double width = Double.parseDouble(widthStr);

            if (length <= 0 || width <= 0) {
                Rectangle rectangle = new Rectangle(name, length, width);
                request.setAttribute("rectangle", rectangle);
                throw new IllegalArgumentException("长度或宽度必须为正数！");
            }

            Rectangle rectangle = new Rectangle(name, length, width);
            request.setAttribute("rectangle", rectangle);

            request.getRequestDispatcher("Success.jsp").forward(request, response);
        } catch (Exception e) {
            request.setAttribute("error", "您输入的信息有误，请重新输入！");
            request.getRequestDispatcher("Error.jsp").forward(request, response);
        }
    }
}